<template>
  <div class="categories-manager">
    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">
        添加分类
      </el-button>
    </div>
    
    <!-- 分类列表 -->
    <el-table
      v-loading="loading"
      :data="categories"
      style="width: 100%; margin-top: 20px;"
    >
      <el-table-column
        prop="name"
        label="名称"
        min-width="150"
      >
        <template slot-scope="scope">
          <i :class="scope.row.icon || 'el-icon-folder'" :style="{ color: scope.row.color }"></i>
          <span style="margin-left: 8px;">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      
      <el-table-column
        prop="description"
        label="描述"
        min-width="200"
        show-overflow-tooltip
      ></el-table-column>
      
      <el-table-column
        prop="icon"
        label="图标"
        width="150"
      >
        <template slot-scope="scope">
          <i :class="scope.row.icon || 'el-icon-folder'"></i>
          <span style="margin-left: 8px;">{{ scope.row.icon }}</span>
        </template>
      </el-table-column>
      
      <el-table-column
        prop="color"
        label="颜色"
        width="100"
      >
        <template slot-scope="scope">
          <div
            class="color-block"
            :style="{ backgroundColor: scope.row.color }"
          ></div>
        </template>
      </el-table-column>
      
      <el-table-column
        prop="bookmarkCount"
        label="书签数量"
        width="100"
        align="center"
      ></el-table-column>
      
      <el-table-column
        label="操作"
        width="150"
        align="center"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            circle
            @click="handleEdit(scope.row)"
          ></el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            circle
            @click="handleDelete(scope.row)"
            :disabled="scope.row.bookmarkCount > 0"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分类表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      @closed="handleDialogClosed"
    >
      <el-form
        ref="form"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            type="textarea"
            v-model="formData.description"
            :rows="3"
            placeholder="请输入分类描述"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="图标" prop="icon">
          <el-input v-model="formData.icon" placeholder="请输入Element UI图标类名">
            <template slot="append">
              <i :class="formData.icon || 'el-icon-folder'"></i>
            </template>
          </el-input>
          <div class="icon-helper">
            <el-link
              type="primary"
              href="https://element.eleme.cn/#/zh-CN/component/icon"
              target="_blank"
            >
              查看图标列表
            </el-link>
          </div>
        </el-form-item>
        
        <el-form-item label="颜色" prop="color">
          <el-color-picker v-model="formData.color"></el-color-picker>
        </el-form-item>
        
        <el-form-item label="排序" prop="order">
          <el-input-number v-model="formData.order" :min="1"></el-input-number>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import {
  getCategories,
  createCategory,
  updateCategory,
  deleteCategory
} from '@/api/category'

export default {
  name: 'CategoriesManager',
  data() {
    return {
      loading: false,
      dialogVisible: false,
      currentCategory: null,
      formData: {
        name: '',
        description: '',
        icon: '',
        color: '#409EFF',
        order: 1
      },
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        icon: [
          { pattern: /^el-icon-/, message: '图标类名必须以 el-icon- 开头', trigger: 'blur' }
        ],
        color: [
          { required: true, message: '请选择颜色', trigger: 'change' }
        ],
        order: [
          { required: true, message: '请输入排序号', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapState(['categories']),
    dialogTitle() {
      return this.currentCategory ? '编辑分类' : '添加分类'
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    async fetchData() {
      this.loading = true
      try {
        await this.$store.dispatch('fetchCategories')
      } catch (error) {
        this.$message.error('获取分类列表失败')
      } finally {
        this.loading = false
      }
    },
    handleAdd() {
      this.currentCategory = null
      this.formData = {
        name: '',
        description: '',
        icon: '',
        color: '#409EFF',
        order: this.categories.length + 1
      }
      this.dialogVisible = true
    },
    handleEdit(category) {
      this.currentCategory = category
      this.formData = { ...category }
      this.dialogVisible = true
    },
    handleDelete(category) {
      if (category.bookmarkCount > 0) {
        this.$message.warning('该分类下还有书签，无法删除')
        return
      }
      
      this.$confirm('确认删除该分类吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteCategory(category._id)
          this.$message.success('删除成功')
          this.fetchData()
        } catch (error) {
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    },
    handleSubmit() {
      this.$refs.form.validate(async valid => {
        if (!valid) {
          return
        }
        
        try {
          if (this.currentCategory) {
            await updateCategory(this.currentCategory._id, this.formData)
            this.$message.success('更新成功')
          } else {
            await createCategory(this.formData)
            this.$message.success('添加成功')
          }
          
          this.dialogVisible = false
          this.fetchData()
        } catch (error) {
          this.$message.error(error.message || '操作失败')
        }
      })
    },
    handleDialogClosed() {
      this.currentCategory = null
      this.$refs.form && this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.categories-manager {
  .color-block {
    width: 20px;
    height: 20px;
    border-radius: 4px;
    display: inline-block;
    vertical-align: middle;
  }
  
  .icon-helper {
    margin-top: 5px;
    font-size: 12px;
  }
}
</style> 